package cn.apestar.common.huanxin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.alibaba.fastjson.JSONObject;

import cn.apestar.common.model.SMap;

public class HttpUtil {

    private static final long serialVersionUID = -8483811141908827663L;

    private static final int TIMEOUT_SECONDS = 200;

    private static final String POST = "POST";

    private static final String GET = "GET";

    private static HttpClient httpClient = null;

    /**
     * 取得HTTPCLIENT 实列
     * @return
     */
    public static HttpClient getHttpClient() {

        HttpClient httpClient = null;
        if (httpClient == null) {
            httpClient = new DefaultHttpClient();
            httpClient = WebClientDevWrapper.wrapClient(httpClient);
            HttpParams httpParams = httpClient.getParams();
            HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SECONDS * 1000);
        }
        return httpClient;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionPost(String URL, List<BasicNameValuePair> formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        if (token != null)
            post.addHeader("Authorization", token); // 认证token
        post.addHeader("Content-Type", "application/json"); // 认证token
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(uefEntity);
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        // if(remoteResponse.getStatusLine().getStatusCode() != 200 &&
        // remoteResponse.getStatusLine().getStatusCode() != 302){
        // throw new RuntimeException("连接失败");
        // }
        entity = remoteResponse.getEntity();
        System.out.println(entity.getContent());
        String endResponseString = getStringAsStream(entity.getContent());
        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionPost(String URL, JSONObject formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        if (token != null)
            post.addHeader("Authorization", token); // 认证token
        post.addHeader("Content-Type", "application/json"); // 认证token
        if (formparams != null) {
            String s = formparams.toString();
            StringEntity se = new StringEntity(formparams.toString(), "utf-8");
            post.setEntity(se);
        }
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            // throw new BaseException(endResponseString);
        }
        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionPostString(String URL, String formparams, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        if (token != null)
            post.addHeader("Authorization", token); // 认证token
        post.addHeader("Content-Type", "application/json"); // 认证token
        if (formparams != null) {
            String s = formparams.toString();
            StringEntity se = new StringEntity(formparams.toString(), "utf-8");
            post.setEntity(se);
        }
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            // throw new BaseException(endResponseString);
        }
        return endResponseString;
    }

    /**
     * 同步执行GET传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionGET(String URL, List<BasicNameValuePair> formparams) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        String url = URL;
        if (formparams != null && formparams.size() > 0) {
            url = url + "&" + URLEncodedUtils.format(formparams, HTTP.UTF_8);
        }
        HttpGet get = new HttpGet(url);

        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(get);

        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException("连接失败");
        }
        entity = remoteResponse.getEntity();
        System.out.println(entity.getContent());
        String endResponseString = getStringAsStream(entity.getContent());
        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String ExecutionDel(String URL, String token) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpDelete post = new HttpDelete(URL);
        if (token != null)
            post.addHeader("Authorization", token); // 认证token
        post.addHeader("Content-Type", "application/json"); // 认证token
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        entity = remoteResponse.getEntity();
        String endResponseString = getStringAsStream(entity.getContent());
        System.out.println(endResponseString);
        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302
            && remoteResponse.getStatusLine().getStatusCode() != 401) {
            throw new RuntimeException("连接失败");
        }

        return endResponseString;
    }

    /**
     * 执行POST传输
     * @param ins
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static void ExecutionAsycPost(String URL, List<BasicNameValuePair> formparams) throws ClientProtocolException, IOException {

        // 获取内容
        HttpEntity entity = null;
        HttpPost post = new HttpPost(URL);
        UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
        post.setEntity(uefEntity);
        HttpClient client = getHttpClient();
        HttpResponse remoteResponse = client.execute(post);

        if (remoteResponse.getStatusLine().getStatusCode() != 200 && remoteResponse.getStatusLine().getStatusCode() != 302) {
            throw new RuntimeException("连接失败");
        }
    }

    /**
     * 取得传输参数
     * @return
     */
    public static List<BasicNameValuePair> getBasicNameValuePair(Map map) {

        List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();

        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            formparams.add(new BasicNameValuePair(s, (String) map.get(s)));
        }

        return formparams;
    }

    /**
     * 对流进行转化
     * @param ins
     * @return
     */
    public static String getStringAsStream(InputStream ins) {

        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(ins, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        StringBuffer sbf = new StringBuffer();
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        /** 回收资源 */
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = sbf.toString();
        return s;
    }

    public static boolean getResult(String action) {

        if (action.contains("error")) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 保存图片
     * @param ImgURL
     */
    public static Map savepic(String ImgURL) {

        if (ImgURL == null) {
            return null;
        }
        HttpGet get = new HttpGet(ImgURL);
        String[] strs = ImgURL.split("/");
        String fileName = strs[strs.length - 1];
        // String savePath = Global.getProjectImagePath() + "/car/"
        // + File.separator + fileName;
        String savePath = "F:/car/" + File.separator + fileName;
        HttpEntity entity = null;
        try {
            HttpResponse response = HttpUtil.getHttpClient().execute(get);
            entity = response.getEntity();
            InputStream is = entity.getContent();
            OutputStream os = new FileOutputStream(savePath);
            IOUtils.copy(is, os);
            IOUtils.closeQuietly(os);
            IOUtils.closeQuietly(is);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("图片保存失败");
            return null;
        }
        return new SMap("name", fileName, "spath", savePath, "path", savePath);
    }

}